package search;

import global.Global;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;

import user.CreateAccount;
import user.CreateAcct;
import user.Login;

import ajaxmethods.SessionMethod;

public class SaveSearch extends SessionMethod {

	//Display the save search bubble
	//The bubble content is dependent on the user having a logged in session
	@Override
	public void perform(HttpServletRequest request, HttpServletResponse response) {
		super.perform(request, response);
		response.setContentType("text/json");
		StringBuffer sb = new StringBuffer();
		Global global = new Global(request);
		if(!global.isLoggedIn.f(request))
		{
			CreateAccount createAcct = new CreateAccount();
			Login login = new Login();
			
			sb.append(createAcct.createAcctJavascript("/map"));
			sb.append(login.loginDlg("savesearch"));
			
		}
		else
		{
			sb=getSaveSearchDlg();
		}
		
		try {
			data.put("savesearch", sb.toString()).write(response.getWriter());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static StringBuffer getSaveSearchDlg()
	{
		StringBuffer sb = new StringBuffer();
		sb.append("<h3 class=\"bubbleheader\">Save Search</h3>");
		sb.append("<div id=\"searchname\"><p class=\"textbox\">"+
		    "<label for=\"searchname\">Search Name</label>"+
		    "<input type=\"text\" class=\"esoinput\" name=\"searchname\" value=\"\" title=\"searchname\" tabindex=\"4\">"+
		    "</p><div class=\"errorText\">&nbsp;</div></div>" +
		    "<button class=\"esobutton\" id=\"savesearch\" onclick=\"performSavedSearch()\" title=\"save search\" type=\"submit\">Save</button>");
		sb.append("<script>");
		sb.append("function performSavedSearch() {");
		sb.append("inputMap = {};" +
				"  inputMap.searchInputs = \".sidepanel input[type='text'],.sidepanel select\";" +
				"  inputMap.genericInputs = \"#bubble input,input[type='hidden']\";" +
				"  doPostWithTypedInputs('search.PerformSaveSearch',inputMap);");
		sb.append("}</script>");
		return sb;
	}

}
